import logging
import re
import urllib.request
import ssl
import bs4
import dealmysql

# 解决urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED]
ssl._create_default_https_context = ssl._create_unverified_context

def get_beautifulsoup(url):
    '''根据url，请求网页，并返回获取到的BeautifulSoup对象
    '''
    response = urllib.request.urlopen(url)
    # ignore解决 can't decode byte 0x8b
    html = response.read().decode('utf-8', "ignore")
    soup = bs4.BeautifulSoup(html, 'lxml')
    return soup

def get_douban_last_set(subject):
    '''抓取豆瓣里的最后一集
    '''
    url = "https://movie.douban.com/subject/" + str(subject)
    soup = get_beautifulsoup(url)
    brief = soup.find_all('a', {'class' : 'item'})

    if not brief:
        # 若豆瓣没找到集数，直接返回None
        logging.warning('没找到豆瓣subject %s 的集数结果' % str(subject))
        return None
        
    last_set = brief[-1].get_text()
    last_set = re.sub(r'[^\d]','', last_set)
    return last_set

def get_aqiyi_zongyi_set(query):
    '''获取爱奇艺的某个指定的搜索结果页面, 
    跳转到综艺详情页，

    Args:
        query: 综艺名字符串
    
    Return: 爱奇艺综艺详情recoAlbumTit-link全部标签
    '''
    # 去除中间空格，否则类似 欢乐喜剧人 第四季 这样的可能搜索不对
    query = query.replace(' ','')
    url = "http://so.iqiyi.com/so/q_"+urllib.parse.quote(query)
    soup = get_beautifulsoup(url)
    brief = soup.find('h3', {'class' : 'result_title'})

    if not brief:
        # 若是没有搜索结果，直接返回None
        logging.warning('爱奇艺中没搜到 %s 的结果' % query)
        return None

    url = brief.find('a').get('href')
    soup = get_beautifulsoup(url)
    brief = soup.find_all('a', {'class' : 'recoAlbumTit-link'})
    return brief

def zongyi_is_finished(query, subject):
    '''检测某综艺是否更新完成
    Args: 
        query: 综艺名字符串
        subject: 豆瓣网对应的subject号
    Returns: yes表示更新完成，no表示未完成，unknown表示未知
    '''
    brief = get_aqiyi_zongyi_set(query)
    last_set = get_douban_last_set(subject)

    if not brief:
        return 'unknown'
    if not last_set:
        return 'unknown'

    for _ in range(len(brief)):
        now_set = brief[_].get_text()
        # 找到 第 字后面的数字，拿去跟豆瓣抓回来的总集数对比
        now_set = re.search(r'第(\d+)', now_set)
        if now_set:
            # 因为可能匹配不到，所以要先判断不为空再进行取数字
            now_set = now_set.group(1)
        if now_set == last_set:
            return 'yes'
    
    return 'no'


if __name__ == "__main__":
    # get_aqiyi_zongyi_set('非凡匠心 第2季')
    # zongyi_is_finished('欢乐喜剧人 第四季', 27665179)
    
    mysql = dealmysql.DealMysql(
        host = "",
        user = "",
        password = "",
        database = "",
        charset='utf8',
        table = 'zongyi_now_playing'
    )
    mysql.connect()
    mysql.delete_all('zongyi_now_playing')

    zongyi_tuple = mysql.select(col_name = ['title', 'subject'], table = 'zongyi_douban_table')
    for item in zongyi_tuple:
        is_finished = zongyi_is_finished(item[0], item[1])
        print(item[0], 'is_finished: ', is_finished)
        mysql.insert([item[1], item[0], is_finished, 'zongyi'])